<template>
  <el-select
    ref="select"
    v-model="data"
    filterable
    remote
    clearable
    :placeholder="placeholder"
    :remote-show-suffix="true"
    :remote-method="select"
    :loading="loading"
    @click="handleClick"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.label"
      :value="item.value"
      @click="handleOptionClick(item)"
    >
      {{ item.selectLabel }}
    </el-option>
  </el-select>
</template>

<script>
import { defineComponent } from "vue";
import useSelectMap from "./useSelectMap.ts";
export default defineComponent({
  props: {
    modelData: {
      type: String,
      default: "",
    },
    placeholder: {
      type: String,
      default: "",
    },
    selectKey: {
      type: String,
      default: "",
    },
  },
  emits: ["update:modelData", "getOption"],
  computed: {
    data: {
      get() {
        return this.modelData;
      },
      set(value) {
        this.$emit("update:modelData", value);
      },
    },
  },
  data() {
    return {
      loading: false,
      options: [],
    };
  },
  methods: {
    handleClick() {
      this.select("");
    },
    select(queryName) {
      if (useSelectMap[this.selectKey]) {
        this.loading = true;
        this.$http
          .get(
            useSelectMap[this.selectKey].url,
            useSelectMap[this.selectKey].returnQueryParam(queryName)
          )
          .then((res) => {
            this.options = useSelectMap[this.selectKey].returnOption(
              res.content
            );
          })
          .finally(() => (this.loading = false));
      } else {
        throw new Error("selectKey不存在");
      }
    },
    /**
     * 返回选择的option
     * @param {object} data - 选择的option
     */
    handleOptionClick(data) {
      this.$emit("getOption", data);
    },
  },
  mounted() {},
});
</script>

<style lang="scss" scoped></style>
